<?php
// 下单商品
// header("content-type:text/html;charset=utf-8");
include_once("conn.php");

//时区设置为中国
date_default_timezone_set('PRC');

//获取当前时间
$now = date('Y-m-d H:i:s');

$oid = "GY" . date('YmdHis') . mt_rand(1000, 9999);
//获取前端传来的数据
$uid = $_POST['uid'];
$goods_id = $_POST['goods_id'];
$address = $_POST['address'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$price = $_POST['price'];
$num = $_POST['num'];
$pay = floatval($price) * floatval($num);

//将数据插入到数据库中

$sql_insert = "INSERT INTO tb_order_info 
        (o_id,uid,g_id,o_address,o_name,o_phone,o_price,o_num,o_pay,o_begintime,o_status) 
        VALUES ('" . $oid . "','" . $uid . "','" . $goods_id . "','" . $address . "','" . $name . "','" . $phone . "','" . $price . "','" . $num . "','" . $pay . "','" . $now . "','0')";

$sql_update = "UPDATE tb_goods_info SET g_sell_num = g_sell_num + " . $num . " WHERE g_id = '" . $goods_id . "'";

if (!empty($_POST['action']) && $_POST['action'] == 'by_cart') {
    $cid = $_POST['c_id'];
    $sql_del = "DELETE FROM tb_cart_info WHERE id = '" . $cid . "'";
    //定义SQL数组
    $sql_arr = array($sql_insert, $sql_update, $sql_del);
}else{
    //定义SQL数组
    $sql_arr = array($sql_insert, $sql_update);
}


//开启事务
mysqli_autocommit($conn, false);

// 定义监测量
$flag = true;
//循环执行SQL
foreach ($sql_arr as $sql) {
    if (!mysqli_query($conn, $sql)) {
        $flag = false;
        //如果有一条SQL执行失败，则回滚数据
        mysqli_rollback($conn);
        echo "<script>alert('下单失败请重试！');history.go(-1);</script>";
        break;
    }
}
if ($flag) {
    //如果所有SQL都执行成功，则提交数据
    mysqli_commit($conn);
    echo "<script>window.location.href='../u_show_order.php';</script>";
}
//关闭数据库连接
mysqli_close($conn);
